<template>
  <view class="task-mask">
    <view class="task-comment-input">
      <u-input
        v-model="comment.content"
        :type="'textarea'"
        :maxlength="comment.commentInputMaxLength"
        :border="false"
        :height="inpitHeight"
        :auto-height="true"
        :custom-style="comment.commentInputStyle"
        :placeholder="placeholder"
        :clearable="false"
        trim
        focus
      />
      <view
        v-viewer="{movable: false}"
        class="task-comment-img-view"
        @click="() => {}"
      >
        <view
          v-for="(file, i) in comment.files"
          :key="i"
          class="task-comment-img-content"
        >
          <u-icon
            class="task-comment-img-close"
            color="#fff"
            name="close-circle"
            size="28"
            @click="removeFile(i)"
          />
          <u-image
            v-if="file.type === 'img'"
            width="100%"
            height="100%"
            :src="file.path"
            border-radiu="6"
          />
          <u-icon
            v-else
            color="#fff"
            name="play-right"
            @click="videoView(file)"
          />
        </view>
      </view>
    </view>
    <view class="task-comment-footer">
      <view>
        <u-icon
          class="task-comment-footer-camera"
          name="camera-fill"
          color="#606266"
          size="58"
          @click="takeFile"
        />
        <u-icon
          name="photo"
          color="#606266"
          size="58"
          @click="takePhotoByCamera"
        />
        <u-upload
          v-show="false"
          ref="uUpload"
          :auto-upload="false"
          :action="'action'"
          :source-type="comment.takePhotoConfig.sourceType"
          :preview-full-image="false"
          :max-size="comment.takePhotoConfig.maxSize"
          multiple
          @on-choose-complete="choosePhoto"
          @on-oversize="comment.takePhotoConfig.onOverSize"
        />
      </view>
      <view class="submitComment-content">
        <view v-show="emitClose" class="task-submitComment" :style="submitColor" @click="modal.show = true">关闭</view>
        <view class="task-submitComment" :style="submitColor" @click="submitComment">{{ submitText }}</view>
      </view>
    </view>

    <u-mask
      :mask-click-able="false"
      :show="videoShow"
      @click="videoShow = false"
    >
      <view class="playerClose">
        <u-icon
          class="close-icon"
          name="plus-circle"
          color="#fff"
          size="48"
          @click="closeVideo"
        />
      </view>

      <view
        v-show="videoShow"
        id="videobox-input"
        ref="videobox"
        class="videobox"
      />
    </u-mask>

    <u-modal
      v-model="modal.show"
      :content="modal.content"
      :title="modal.title"
      :cancel-text="'取消'"
      show-cancel-button
      @confirm="modal.startEmitClose"
    />
    <!-- 压缩工具 -->
    <w-compress ref="wCompress" :pixels="500000" />
  </view>
</template>

<script type="text/ecmascript-6">
/* eslint-disable no-undef */

import { conversionBase64 } from '@/utils/utils';
import _ from 'lodash';
import { Message } from '@/utils/utils';
import DPlayer from 'dplayer';
import WCompress from '@/components/w-compress/w-compress.vue';

export default {
  components: { WCompress },

  props: {
    // 是否发送关闭事件
    emitClose: {
      type: Boolean,
      default: false
    },

    // 点击发送的回调
    inputCallBack: {
      type: Function,
      default: () => {}
    },

    // input 高度
    inpitHeight: {
      type: Number,
      default: 170
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    submitText: {
      type: String,
      default: '发送'
    },
    submitColor: {
      type: Object,
      default: () => {
        return {
          color: '#2979FF'
        };
      }
    }
  },

  data() {
    return {
      path: '',
      modal: {
        show: false,
        content: '关闭后数据不会被保存',
        title: '确认关闭',
        request: {},
        startEmitClose: () => {
          this.$emit('close');
        }
      },
      videoShow: false,
      dbPlayer: {},

      videoContext: {},
      comment: {
        inpitHeight: 170,
        showCommentInput: false,
        commentInputMaxLength: 350,
        content: '',
        files: [],
        commentInputStyle: {
          'padding': '12px'
        },
        takePhotoConfig: {
          fileList: [],
          videos: [],
          sourceType: ['album', 'camera'] // ['album', 'camera']
        }
      }

    };
  },

  methods: {
    closeMask() {
      if (this.emitClose) {
        this.modal.show = true;
      }
    },

    async videoView(file) {
      const { path } = file;
      const { url, blob } = await this.getUrlWay(path);
      const envir = this.envirCurr();
      file.blob = blob;
      this.path = path;
      this.videoShow = true;
      setTimeout(() => {
        const el = document.querySelector('#videobox-input');
        const dp = new DPlayer({
          container: el,
          autoplay: true,
          video: {
            url: envir === 'ios' ? url : file.b64
          }
        });

        this.dbPlayer = dp;
      }, 500);
    },

    // 当前环境
    envirCurr() {
      const u = navigator.userAgent;
      const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; // g
      const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
      if (isAndroid) {
        // 这个是安卓操作系统
        return 'anzhuo';
      }
      if (isIOS) {
        // 这个是ios操作系统
        return 'ios';
      }
    },

    getUrlWay(url) {
      const self = this;
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onreadystatechange = function(e) {
          const { currentTarget } = e;
          if (xhr.readyState === 4 && xhr.status === 200) {
            self.path = currentTarget.responseURL;
            resolve({ url: currentTarget.responseURL, blob: currentTarget.response });
            // now url is ready
          }
        };
        xhr.send();
      });
    },

    closeVideo() {
      this.dbPlayer.destroy();
      this.videoShow = false;
    },

    checkedFileLength() {
      const flag = this.comment.files.length < 9;
      if (!flag) {
        Message('最多支持9个文件');
      }
      return flag;
    },

    // 视频
    takeFile() {
      if (!this.checkedFileLength()) {
        return;
      }
      const flag = this.comment.files.some(file => file.type === 'video');

      if (flag) {
        Message('最多上传一份视频');
      } else {
        uni.chooseVideo({
          count: 9,
          sourceType: ['camera', 'album'],
          success: (res) => {
            const { tempFile: file, tempFilePath: path } = res;
            const video = {
              path,
              type: 'video',
              file
            };
            if (/^video/.test(file.type)) {
              this.covserB64(file).then(b64 => {
                video.b64 = b64;
                this.comment.files.push(video);
              });
            } else {
              Message('请选择视频');
            }
          }
        });
      }
    },

    // 视频
    playVideo(file) {
      // const reader = new FileReader();
      // reader.readAsDataURL(file);
      // reader.onload = e => {
      //   const { target: { result }} = e;
      //   this.comment.takePhotoConfig.videos = [{ file, src: result }];
      // };
      const url = URL.createObjectURL(file);
      this.comment.takePhotoConfig.videos = [{ file, src: url }];
    },

    covserB64(file) {
      return new Promise((resolve) => {
        const aBlob = new Blob([file], { type: file.type });
        const reader = new FileReader();
        reader.onload = (ev) => {
          resolve(ev.target.result);
        };
        reader.readAsDataURL(aBlob);
      });
    },

    dealSelFile(files) {
      const dealFiles = files.map((file) => {
        const fileInfo = {
          path: URL.createObjectURL(file),
          file
        };

        if (/mp4/g.test(file.type)) {
          fileInfo.type = 'video';
        } else {
          fileInfo.type = 'img';
        }

        return fileInfo;
      });

      const promise = new Promise((resolve) => {
        dealFiles.forEach((file, index) => {
          this.covserB64(file.file).then(b64 => {
            file.path = b64;
            if (index === dealFiles.length - 1) {
              resolve();
            }
          });
        });
      });

      promise.then(() => {
        const tempFilePaths = dealFiles.map(file => file.path);
        uni.showLoading({
          title: '压缩中'
        });
        this.$refs.wCompress.start(tempFilePaths).then((res) => {
          uni.hideLoading();
          res.forEach((b64, index) => {
            dealFiles[index].path = b64;
            dealFiles[index].file = this.dataURLtoFile(b64, dealFiles[index].file.name);
          });
          this.comment.files = this.comment.files.concat(dealFiles);
        });
      });
    },

    dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },

    removeFile(i) {
      this.comment.files.splice(i, 1);
      URL.revokeObjectURL(this.path);
    },

    getContent() {
      return _.cloneDeep(this.comment);
    },

    submitComment() {
      const data = this.comment;
      if (this.comment.files.length > 9) {
        Message('最多支持9个文件');
        return;
      }
      if (data.content === '' && data.files.length === 0) {
        Message('内容为空');
      } else {
        this.inputCallBack(this.getContent());
      }
      // this.clearData();
    },

    clearData() {
      this.getUpload().clear();
      this.comment.takePhotoConfig.fileList = [];
      this.comment.content = '';
      this.comment.files = [];
    },

    getUpload() {
      return this.$refs.uUpload;
    },

    // 获取照片
    takePhotoByCamera() {
      if (!this.checkedFileLength()) {
        return;
      }
      uni.chooseImage({
        success: res => {
          const { tempFiles } = res;
          if (tempFiles.every(file => {
            return /^image/.test(file.type);
          })) {
            this.dealSelFile(tempFiles);
          } else {
            uni.showToast({
              title: '只允许上传图片格式',
              duration: 2000,
              icon: 'none'
            });
          }
        }
      });
    },

    choosePhoto(fileList) {
      const files = fileList.map((file, index) => {
        return {
          index,
          file: file.file
        };
      });

      files.forEach(async(file, i) => {
        file.b64 = await conversionBase64(file.file);
        if (i === files.length - 1) {
          this.comment.takePhotoConfig.fileList = files;
        }
      });
    }
  }

};
</script>

<style lang="scss" scoped>
.task-comment-input {
  margin: 12px 8px;
  background-color: #EAECF0;
  border-radius: 14px;
  max-height: 80vh;
  overflow: scroll;
  .task-comment-img-view {
    padding: 12px 8px;;
    min-height: 30px;
    display: grid;
    gap: 10px 13px;
    grid-template-columns: repeat(auto-fill, minmax(44px, 1fr));
    > view {
      height: 44px;
    }

    .task-comment-img-content {
      position: relative;
      background-color: #858585;
      display: flex;
      justify-content: center;
      align-items: center;
      .task-comment-img-close {
        position: absolute;
        right: -5px;
        top: -5px;
        z-index: 12;
        background-color: red;
        border-radius: 60px;
      }
    }
  }
}

.task-comment-footer {
    display: flex;
    justify-content: space-between;
    padding: 0 24px;
    .task-comment-footer-camera {
      margin-right: 24px;
    }

    .task-submitComment {
      // color: #2979FF;
      font-weight: 600;
    }
  }

  .playerClose {
    height: 44px;
    width: calc(100% - 24px);
    margin: 0 12px;
    display: flex;
    align-items: flex-end;
    padding-bottom: 6px;
    flex-direction: row-reverse;
    .close-icon {
      transform: rotate(45deg);
    }
  }
  .videobox {
    z-index: 9999999;
    width: calc(100% - 24px);
    height: calc(100vh - 80px);
    margin: 0 12px;
    overflow: hidden;
    background-color: #F1F1F1;
    .playerClose {
      position: absolute;
      z-index: 99999999;
      right: 0;
      top: 0;
      color: #fff;
    }
  }

  .task-mask {
    width: 100%;
    height: 100vh;
    background-color: #fff;
  }

  .submitComment-content {
    display: flex;

    > view {
      &:first-child {
        margin-right: 20px;
      }
    }
  }
</style>
